#include "uicontroller.h"
#include "mc_uiprotocol.h"

UIController::UIController(QObject *parent) : QObject(parent)
{
    mp_SDController = new SDController;
    mp_SPController = new SPController;

    engine.rootContext()->setContextProperty("RootController" , this);

    engine.rootContext()->setContextProperty("SDController" , mp_SDController);
    engine.rootContext()->setContextProperty("SPController" , mp_SPController);


    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return;

    mp_SDController->setSDQmlViewRootItem(engine.rootObjects().at(0));
//    mp_SPController->setSPQmlViewRootItem(engine.rootObjects().at(0));
//    qDebug()<<engine.rootObjects().at(0)->findChild<QObject*>("objsdbuildview");




    mpGuiSHM = new QueueShareMemory(QSharedMemory::ReadWrite , QSharedMemory::ReadOnly , get_mc_info("[SHM]" , "shmonekey").toString() , get_mc_info("[SHM]" , "shmtwokey").toString());
    connect(&mt_ReadSHMTimer , &QTimer::timeout , this ,&UIController::readSHMTimerEvent);
    mt_ReadSHMTimer.start(20);

//    mpGuiSHM->writeSHMData(QByteArray("I am GUI 1"));
//    mpGuiSHM->writeSHMData(QByteArray("I am GUI 2"));
//    mpGuiSHM->writeSHMData(QByteArray("I am GUI 3"));
//    mpGuiSHM->writeSHMData(QByteArray("I am GUI 4"));
}
void UIController::readSHMTimerEvent()
{
    GUI_SHM_PACKET_HEADER *pHeader = NULL;
    if(mpGuiSHM->getSHMData(mq_SHMData)){
        foreach (QByteArray data, mq_SHMData) {
            pHeader = (GUI_SHM_PACKET_HEADER*)(data.data());
            if(data.length() < pHeader->packetsize){
                qDebug()<<FLINE<<"Got SHM Data Size Not Enough Packet Size:"<<pHeader->packetsize<<" Data Len:"<<data.data();
                return;
            }

            if(pHeader->devtype == DEVICE_CLOUD){
                processData(data);
                return;
            }

            mp_SDController->processData(data);
            mp_SPController->processData(data);
        }
    }
}
QVariant UIController::getMcConfigInfo(QString groupname, QString keyname)
{
    return get_mc_info(groupname , keyname);
}
void UIController::processData(QByteArray data)
{
    GUI_SHM_PACKET_HEADER *pHeader = (GUI_SHM_PACKET_HEADER*)data.data();
    GUI_SHM_LT_INFO *pLtInfo = (GUI_SHM_LT_INFO*)(data.data()+sizeof(GUI_SHM_PACKET_HEADER));


    QString cloudtype = "Cloud";
    QString event = "";
    if(pLtInfo->cmd == CMD_GUI_DEVICE_ON){
        event = "Online";
    }
    else if(pLtInfo->cmd == CMD_GUI_DEVICE_OFF){
        event = "Offline";
    }

    rootWinEvent(cloudtype , event);
}
